package com.appkudos.view;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;
import java.util.List;

import com.appkudos.controller.GroupController;
import com.appkudos.model.Recommendation;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TwoLineListItem;
 
public class RecArrayAdapter extends ArrayAdapter {
 
	private final int resourceId;
 
	public RecArrayAdapter(Context context, int textViewResourceId, List objects) {
		super(context, textViewResourceId, objects);
		resourceId = textViewResourceId;
	}
 
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
 
		Recommendation r = (Recommendation) getItem(position);
		GroupController gc = new GroupController();
		
		// if the array item is null, nothing to display, just return null
		if (r == null) {
			return null;
		}
 
		// We need the layoutinflater to pick up the view from xml
		LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
 
		// Pick up the TwoLineListItem defined in the xml file
		TwoLineListItem view;
		if (convertView == null) {
			view = (TwoLineListItem) inflater.inflate(resourceId, parent, false);
		} else {
			view = (TwoLineListItem) convertView;
		}
 
		// Set value for the first text field
		if (view.getText1() != null) {
			String name = r.getReceiver();
			if(r.isGroupRecipient()){
				name = gc.getGroupById(r.getReceiver()).getGroupName();
			}
			DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM);
			Date d = new Date();
			try {
				d = df.parse(r.getDateSent().substring(0, 10));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			String date = df.format(d);
			view.getText1().setText(r.getSender() + " to " + name + " on " + date + ":");
		}
 
		// set value for the second text field
		if (view.getText2() != null) {
			view.getText2().setText("\"" + r.getMessage() + "\"");
		}
 
		return view;
	}
 
}